package com.xfc.config;

import com.alibaba.fastjson.JSON;
import com.xfc.wx.domain.AuthToken;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class WxUtil {

    /**
     * 根据code获取微信授权access_token
	 */
    public static AuthToken getTokenByAuthCode(String code, String appid, String app_secret) {
        AuthToken authToken = null;
        StringBuilder json = new StringBuilder();
        try {
            URL url = new URL(Authtoken_URL(code, appid, app_secret));
            System.out.println("tokenURL----"+url);
            URLConnection uc = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            System.out.println("tokenjson---"+json.toString());
            // 将json字符串转成javaBean
            authToken = JSON.parseObject(json.toString(), AuthToken.class);
        } catch (IOException ex) {
            System.out.println("获取access_token异常");
        }
        return authToken;
    }

    /**
     * 通过code获取授权access_token的URL
     */
    public static String Authtoken_URL(String code,String appid,String app_secret) {
        StringBuffer url = new StringBuffer();
        url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        url.append(appid);
        url.append("&secret=");
        url.append(app_secret);
        url.append("&code=");
        url.append(code);
        url.append("&grant_type=authorization_code");
        return url.toString();
    }

}
